import 'package:flutter/material.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/book/BookFolders.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'newOrEditFolderDialog.dart';

// ignore: must_be_immutable
class AddToFolderDialog extends StatefulWidget {
  AddToFolderDialog({
    Key? key,
    required this.readingType,
    required this.title,
    required this.selected,
    required this.message,
    required this.readingTypeFrom,
  }) : super(key: key);

  String title;
  final List<String> selected;
  String message;
  NanhaiBookReadingTypes readingType;
  String readingTypeFrom;

  _AddToFolderDialogState createState() => new _AddToFolderDialogState();
}

class _AddToFolderDialogState extends State<AddToFolderDialog> {
  final BooksController _booksController = Get.find();
  final folderIdController = TextEditingController();
  final box = Hive.box('appconfig');
  bool isTeacher = false;
  String _folderId = '';

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    super.initState();
  }

  void _addToFolder() async {
    Log.debug(_folderId);
    if (_folderId != '' && widget.selected.length > 0) {
      _booksController
          .addBooksToLibraryFolder(
              _folderId, widget.selected, widget.readingType)
          .then((data) {
        if (data.message != null && data.status == 1000) {
          _booksController.selectedThemedBookItemsClear();
          _booksController.selectedFavoriteReadingBookItemsClear();
          _booksController.selectedLibraryReadingBookItemsClear();
          showSnackMsg(isTeacher
              ? 'Book(s) added to lesson plan successfully'
              : 'Book(s) added to folder successfully');
          // Get.snackbar('Message'.tr, isTeacher ?'Book(s) added to lesson plan successfully'.tr : 'Book(s) added to folder successfully'.tr,
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
          Navigator.of(context).pop();
        } else {
          showSnackMsg(
              data.message ?? 'Error to add book(s) to lesson plan / folder');
          // Get.snackbar('Message'.tr,
          //     data.message ?? 'Error to add book(s) to lesson plan / folder',
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
        }
      });
    }
  }

  void onFolderChange(AllFolder? folder) {
    if (folder != null) _folderId = folder.id.toString();
  }

  @override
  void dispose() {
    _booksController.fetchBookAllFolders();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    return AlertDialog(
      title: Text(widget.title.tr),
      titleTextStyle: TextStyle(
          fontWeight: FontWeight.bold,
          letterSpacing: 1,
          color: Get.isDarkMode ? Color(0xffcccccc) : Colors.black,
          fontSize: 20),
      backgroundColor: Get.isDarkMode
          ? (Color(0xff333333))
          : Color.fromARGB(255, 234, 241, 238),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(20))),
      content: Container(
        height: 200,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                  child: Obx(() {
                    if (_booksController.bookFolders.length > 0) {
                      return Container(
                        width: 380,
                        child: DropdownButtonFormField(
                          decoration: InputDecoration(
                            labelText: isTeacher
                                ? 'Choose Lesson Plan'.tr
                                : 'Choose Folder'.tr,
                          ),
                          validator: FormBuilderValidators.compose(
                              [FormBuilderValidators.required()]),
                          items: _booksController.bookFolders
                              .map((folder) => DropdownMenuItem(
                                    value: folder,
                                    child: Text('${folder.folderName}'),
                                  ))
                              .toList(),
                          onChanged: onFolderChange,
                        ),
                      );
                    } else {
                      return Text('');
                    }
                  }),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                MaterialButton(
                    color: Get.isDarkMode
                        ? (Colors.white)
                        : Theme.of(context).primaryColorDark,
                    textColor: Get.isDarkMode
                        ? (Colors.black)
                        : Theme.of(context).primaryColorLight,
                    onPressed: () {
                      Navigator.of(context).pop();
                      showGeneralDialog(
                          context: context,
                          transitionDuration: Duration(milliseconds: 400),
                          pageBuilder: (bc, ania, anis) {
                            return NewOrEditFolderDialog(
                                title: isTeacher
                                    ? 'Create Lesson Plan'.tr
                                    : 'Create Folder'.tr,
                                message: '',
                                type: 'create');
                          });
                    },
                    child: Text('Create New Folder'.tr)),
                SizedBox(
                  width: 20,
                ),
                MaterialButton(
                    color: Get.isDarkMode
                        ? (Colors.white)
                        : Theme.of(context).primaryColorDark,
                    textColor: Get.isDarkMode
                        ? (Colors.black)
                        : Theme.of(context).primaryColorLight,
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text('Cancel'.tr)),
                SizedBox(
                  width: 20,
                ),
                MaterialButton(
                    color: Get.isDarkMode
                        ? (Colors.white)
                        : Theme.of(context).primaryColorDark,
                    textColor: Get.isDarkMode
                        ? (Colors.black)
                        : Theme.of(context).primaryColorLight,
                    onPressed: () {
                      _addToFolder();
                    },
                    child: Text('Submit'.tr)),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
